package com.system.permissiondemo.interceptor;

import com.system.permissiondemo.common.RequestHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description:    Http拦截
 * @Author:         Joe
 * @CreateDate:     2019/9/10 21:27
 */
@Service
@Slf4j
public class HttpInterceptor implements HandlerInterceptor {

    private static final String START_TIME = "requestStart_Time";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI().toString();
        log.info("pre url:{}",url);
        Long start = System.currentTimeMillis();
        request.setAttribute(START_TIME,start);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String url = request.getRequestURI().toString();
        Long start = (Long) request.getAttribute(START_TIME);
        Long  end = System.currentTimeMillis();
        request.setAttribute(START_TIME,start);
        log.info("after url:{},times:{}",url,end-start);
        removeThreadLocalInfo();
    }

    /**
     * 移除信息
     */
    public void removeThreadLocalInfo(){
        RequestHolder.remove();
    }
}
